package com.app.interceptor;

import java.util.Enumeration;
import java.util.Map;

import com.app.conf.AppConfig;
import com.app.conf.info.Conf;
import com.app.controller.BaseController;
import com.app.util.db.ConnLessDBSource;
import com.app.util.log.Loging;
import com.app.util.tools.ThreadCache;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.DbKit;

public class GlobalActionInterceptor implements Interceptor
{

	@Override
	public void intercept(Invocation invocation)
	{
		Loging loging              = AppConfig.getAppConfig().getLogger();
		ThreadCache cache          = AppConfig.getAppConfig().getCache();
		
		BaseController bc          = (BaseController)invocation.getController();
		Enumeration<String> params = bc.getParaNames();
		String param               = "";

		cache.addln("");
		cache.addln("key:"+invocation.getActionKey());
		
        while (params.hasMoreElements())
        {
            param = params.nextElement();
            cache.addln(param+":"+bc.getPara(param));
        }
		
		try
		{
			invocation.invoke();
		} 
		catch (Exception e)
        {
            e.printStackTrace();
        }
		finally
		{
			//输出缓存中的日志
			loging.info(cache.get());cache.del();
			
			//释放数据源缓存
			releaseCache();
		}
	}
	
	/**
	 * 释放全部数据源的线程缓存
	 * **/
	private void releaseCache()
	{
		ConnLessDBSource dbSource = null;
		Config config             = null;	
		
		for(Map<String,String> item : Conf.getDbs())
		{
		    config = DbKit.getConfig(item.get("name"));

		    if(null != config)
		    {
		        dbSource = (ConnLessDBSource)config.getDataSource();dbSource.gettCache().remove();
		    }
		}
	}

}